#include "degfx/bitmap.h"

unsigned mx_bitmap_collision(const MX_BITMAP * src, const MX_BITMAP * dest, int sx, int sy, int dx, int dy, unsigned int thresh)
{
	int y;
	MX_RECT d;
	MX_RECT s;
	MX_RECT inter;

	d = *MXRECT(dest);
	s = *MXRECT(src);

	/* Translate destnation area to source */
	d.x1 += dx;
	d.y1 += dy;
	d.x2 += dx;
	d.y2 += dy;
	s.x1 += sx;
	s.y1 += sy;
	s.x2 += sx;
	s.y2 += sy;

	/* Check for overlap in the areas */
	MXRECT_INTERSECT(s, d, inter);
	if (!MXRECT_VALID(inter))
		return false;

	/* Check for overlapping pixels */
	for (y = inter.y1; y <= inter.y2; y++) {

		MX_BITMAP_ITER srci = mx_bitmap_iter(src, inter.x1 - sx, y - sy);
		const MX_BITMAP_ITER endi = mx_bitmap_iter(src, inter.x2 - sx, y - sy);

		MX_BITMAP_ITER dsti = mx_bitmap_iter(dest, inter.x1 - dx, inter.y1 - dy);

		while (srci <= endi) {
			/** Collision is defined by both bitmaps having a transparency
                less than the threshold on overlapping pixels. */
			if ((MXT(*srci) < thresh) && (MXT(*dsti) < thresh))
				return true;

			++srci;
			++dsti;
		}
	}
	return false;
}
